package com.hmall.item.web;

import com.hmall.category.pojo.Category;
import com.hmall.common.PageBean;
import com.hmall.item.service.CategoryService;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * (TbCategory)表控制层
 *
 * @author makejava
 * @since 2024-06-29 15:08:33
 */
@RestController
@RequestMapping("/category")
public class CategoryController {
    /**
     * 服务对象
     */
    @Resource
    private CategoryService categoryService;

    /**
     * 分页查询
     *
     * @param page 页码
     * @param size 每页大小
     * @return 查询结果
     */
    @GetMapping("/list")
    public PageBean<Category> queryByPage(@RequestParam(value = "page") int page,
                                          @RequestParam(value = "size") int size) {
        List<Category> categoryList = categoryService.queryByPage(page, size);
        long total = categoryService.getTotal();
        PageBean<Category> pageBean = new PageBean<>();
        pageBean.setList(categoryList);
        pageBean.setTotal(total);
        return pageBean;
    }

    /**
     * 新增数据
     *
     * @param category 实体
     * @return 新增结果
     */
    @PostMapping
    public ResponseEntity<Void> addItem(@Validated @RequestBody Category category) {
        categoryService.addCategory(category);
        return ResponseEntity.ok().build();
    }

    /**
     * 编辑数据
     *
     * @param category 实体
     * @return 编辑结果
     */
    @PutMapping
    public ResponseEntity<Void> update(@RequestBody Category category) {
        // 判断id是否为空，如果不为空则更新数据
        if (category.getId() != null) {
            // 更新数据
            categoryService.update(category);
            // 返回更新成功
            return ResponseEntity.ok().build();
        } else {
            // 如果id为空，则不更新数据
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteById(@PathVariable Long id) {
        categoryService.deleteById(id);
        return ResponseEntity.ok().build();
    }

}

